<?php

namespace app\common\logic;

use app\common\library\exception\ApiException;
use app\common\library\MemberVo;
use app\common\model\Agent;
use app\common\model\AgentMoneyRecord;
use app\common\model\Car;
use app\common\model\Config;
use app\common\model\Coupon;
use app\common\model\Goods;
use app\common\model\Member;
use app\common\model\Message;
use app\common\model\MoneyRecord;
use app\common\model\Order;
use app\common\model\OrderCommission;
use app\common\model\PlatformMoneyRecord;
use app\common\model\ServiceTimes;
use app\common\model\Shop;
use think\Db;
use think\db\Query;
use think\Env;
use think\Exception;
use think\Log;

class AuditLogic extends BaseLogic
{
    public $model;

    public $resourceHandle;

    public function assignModel()
    {
        /** @var Order $model */
        $this->model          = new Order();
    }

    public function handleSearch(Query $query, array $params): Query
    {
        return $query;
    }

    public function detail($params)
    {
        $order = Order::field('id,order_sn,order_amount,order_status,payment_time,audit_code,pay_amount,coupon_id,coupon_money,pay_type')
            ->where(['order.audit_code'=>$params['audit_code'],'order.shop_id'=>MemberVo::instance()->getShopId()])->with(['orderGoods', 'car','shop','coupon'])->find();
        if (empty($order))
            throw new ApiException('店铺中无该订单信息',404);
        $order['car_numbers'] = $order['car']['car_numbers'];//车牌号
        $order['goods_detail'] = Goods::where('id',$order['order_goods'][0]['goods_id'])->value('goods_detail');//服务内容 项目简介
        $order['coupon_name'] = '';//优惠券名称
        if ($order['coupon_id'] > 0){
            $coupon_info = Coupon::where('coupon.id',$order['coupon_id'])->with('couponSetting')->find();
            $order['coupon_name'] = $coupon_info['couponSetting']['name'];
        }
        unset($order['car'],$order['shop'],$order['coupon']);
        return $order;
    }


    /**
     * 更改订单车牌号
     * @param $params
     * @return bool
     * @throws ApiException
     * @throws \think\exception\DbException
     */
    public function change_car_numbers($params)
    {
        //查询订单信息
        $order_info = Order::get(['id'=>$params['order_id'],'shop_id'=>MemberVo::instance()->getShopId()]);
        if (!$order_info)
            throw new ApiException('店铺中无该订单信息',404);
        if ($order_info['order_status'] == 0){
            throw new ApiException('该订单已取消',404);
        }elseif ($order_info['order_status'] == 1){
            throw new ApiException('该订单未支付',404);
        }elseif (in_array($order_info['order_status'],[3,4,5])){
            throw new ApiException('该订单已核销',404);
        }
        //查询车辆信息
        $car_info = Car::get(['member_id'=>$order_info['member_id'],'car_numbers'=>$params['car_numbers']]);
        if ($car_info){
            if ($car_info['id'] == $order_info['car_id'])
                throw new ApiException('车牌与订单车牌一致，无需更改',404);
            $order_info->save(['car_id'=>$car_info['id']]);
        }else{
            $res = Car::create(['member_id'=>$order_info['member_id'],'car_numbers'=>$params['car_numbers']]);
            $order_info->save(['car_id'=>$res->id]);
        }
        return true;
    }


    /**
     * 确认核销
     * @param $params
     * @return bool
     * @throws ApiException
     * @throws \think\exception\DbException
     */
    public function audit_confirm($params)
    {
        Db::startTrans();
        try{
            //查询订单信息
            $order_info = Order::get(['audit_code'=>$params['audit_code'],'shop_id'=>MemberVo::instance()->getShopId()]);
            if (!$order_info)
                throw new Exception('店铺中无该订单信息');
            if ($order_info['order_status'] == 0){
                throw new Exception('该订单已取消');
            }elseif ($order_info['order_status'] == 1){
                throw new Exception('该订单未支付');
            }elseif (in_array($order_info['order_status'],[3,4,5])){
                throw new Exception('该订单已核销');
            }
            $order_info->audit_time = time();
            $order_info->order_status = 3;
            $order_info->save();
            $order_income = bcsub($order_info['pay_amount'], $order_info['cost'], 2);//获取利润金额 （实际支付金额 - 成本）
            //给代理商转钱
            $info = OrderCommission::get(['order_id'=>$order_info->id]);
            if ($info){
                $money = bcadd($info['cost'],$info['money'],3);//计算 佣金+成本总额
                $balance = Agent::where('id',$info['agent_id'])->value('money');//余额
                Agent::where('id',$info['agent_id'])->setInc('money',$money);//代理商增加金额
                AgentMoneyRecord::insertAll([
                    ['type'=>1,'money'=>$info['cost'],'balance'=>bcadd($balance,$info['cost'],3),'order_id'=>$order_info->id,'agent_id'=>$info['agent_id'],'createtime'=>time()],//成本返还
                    ['type'=>2,'money'=>$info['money'],'balance'=>bcadd($balance,$money,3),'order_id'=>$order_info->id,'agent_id'=>$info['agent_id'],'createtime'=>time()],//分佣
                ]);
                $info->status = 1;
                $info->save();
                $order_income = bcsub($order_income, $info['money'], 3);
            }
            //平台订单收益记录
            PlatformMoneyRecord::create(['type'=>1,'detail_type'=>PlatformMoneyRecord::DETAIL_TYPE_ORDER_PROFIT,'money'=>$order_income,'remark'=>$order_info->id,'createtime'=>time()]);
            //给商家余额扣钱
            $shop_info = Shop::get($order_info['shop_id']);
            if (empty($shop_info))
                throw new Exception('店铺信息不存在');
            $shop_balance = bcsub($shop_info['money'],$order_info['cost'],2);//商家余额 = 余额 - 订单成本
            if ($shop_balance < 0)
                throw new Exception('店铺余额不足，请管理员申请充值');
            $shop_info->money = $shop_balance;
            $shop_info->save();
            MoneyRecord::create(['type'=>2,'detail_type'=>4,'money'=>$order_info['cost'],'balance'=>$shop_balance,'shop_id'=>$order_info['shop_id'],'order_id'=>$order_info['id'],'remark'=>'商家余额扣除']);
            //计算客户服务次数
            $service_num = Config::where(['name'=>'service_num'])->value('value');//系统设置的达标次数
            Log::info($service_num);
            $days = intval(Env::get('app.days',180));
            $days = $days-1;
            //当前时间往前推180的总核销数
            $service_times = Order::whereBetween('audit_time',[strtotime(date('Y-m-d',strtotime("-{$days} days"))),time()])->where(['member_id'=>$order_info->member_id])->whereIn('order_status',[3,4])->count('id');
            Log::info($service_times);
            if ($service_times >= $service_num){ //如果180天超过了设置的服务单数
                Log::info(111111);
                $service_times_info = ServiceTimes::where(['member_id'=>$order_info['member_id']])->find();
                Log::info($service_times_info);
                if (empty($service_times_info)){//之前未有vip记录
                    Log::info(77777777);
                    ServiceTimes::create(['member_id'=>$order_info['member_id'],'begin_time'=>time(),'end_time'=>strtotime(date('Y-m-d 23:59:59',strtotime("+{$days} day"))),'is_vip'=>1]);//新增vip过期数
                }else{
                    Log::info(8888888);
                    $service_times_info->is_vip = 1;
                    //判断是否已经过期
                    if ($service_times_info->end_time < time()){//之前的VIP已过期
                        Log::info(99999999);
                        $service_times_info->begin_time = time();
                        $service_times_info->end_time = strtotime(date('Y-m-d 23:59:59',strtotime("+{$days} day")));
                    }else{//之前的VIP未过期
                        Log::info(16161);
                        $service_times_info->end_time = strtotime(date('Y-m-d 23:59:59',strtotime("+{$days} day")));//延长过期天数
                    }
                    Log::info(2222222);
                    $service_times_info->save();
                }
                Log::info(123123);
                Member::update(['is_vip'=>1],['id'=>$order_info['member_id']]);
            }
            //添加站内信
            $critical = Config::where(['name'=>'critical'])->value('value');//系统设置的达标次数
            if (empty($critical))
                $critical = 0.3;
            if ($shop_balance < bcmul($shop_info['fixed_amount'],$critical,1)){//余额小于单次固定充值金额的30%，即发站内信
                Message::create(['agent_id'=>$info['agent_id'],'content'=>$shop_info['shop_name'].'余额即将不足，请及时通知充值！']);
                Message::create(['content'=>$shop_info['shop_name'].'余额即将不足，请及时通知充值！']);
            }
            Db::commit();
            return true;
        }catch (Exception $e){
            Db::rollback();
            throw new ApiException($e->getMessage(),404);
        }

    }

}